// tabelDatasets.js
class DatasetsTableCloud {
    constructor(app, db) {
        this.app = app;
        this.db = db;
    }

    init() {
        // 创建dataset list表结构
        const sqlDatasetsTable = `
        CREATE TABLE IF NOT EXISTS datasets_cloud (
            id TEXT PRIMARY KEY,
            dataset_name TEXT NOT NULL,
            dataset_supertype TEXT NOT NULL,
            dataset_type TEXT NOT NULL,
            label_format TEXT,
            dataset_dir TEXT NOT NULL,
            download_url TEXT NOT NULL,
            dataset_desc TEXT,
            total_samples INTEGER,
            labeled_samples INTEGER,
            create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );`;

        this.db.run(sqlDatasetsTable, (err) => {
            if (err) {
                console.error('Create "datasets_cloud" Table Failed, Error: ', err);
            }
        });
    }

    async insertDataset(datasetInfos) {
        const { id, dataset_name, dataset_supertype, dataset_type, label_format, dataset_dir, download_url, dataset_desc, total_samples, labeled_samples } = datasetInfos;
        // console.log('labelFormat = ', labelFormat);
        return new Promise((resolve, reject) => {
            const sqlInsert = `
                INSERT INTO datasets_cloud (id, dataset_name, dataset_supertype, dataset_type, label_format, dataset_dir, download_url, dataset_desc, total_samples, labeled_samples, create_time, update_time)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime(CURRENT_TIMESTAMP, '+8 hour') , datetime(CURRENT_TIMESTAMP, '+8 hour'));`;
            this.db.run(
                sqlInsert,
                [id, dataset_name, dataset_supertype, dataset_type, label_format, dataset_dir, download_url, dataset_desc, total_samples, labeled_samples],
                function (err) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(id);
                    }
                }
            );
        });
    }

    // 获取dataset的基础信息
    async getDatasetInfo(datasetId) {
        // console.log('datasetId = ', datasetId);
        return new Promise((resolve, reject) => {
            const sqlQuery = `SELECT * FROM datasets_cloud WHERE id = ?`;
            this.db.all(sqlQuery, [datasetId], (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(rows[0]);
                }
            });
        });
    }

    // 读取数据集列表
    async getDatasetList(datasetSuperType, datasetType) {
        return new Promise((resolve, reject) => {
            let sqlQuery = `SELECT * FROM datasets_cloud`;
            const conditions = [];
            const params = [];

            if (datasetSuperType) {
                conditions.push(`dataset_supertype = ?`);
                params.push(datasetSuperType);
            }

            if (datasetType) {
                conditions.push(`dataset_type = ?`);
                params.push(datasetType);
            }

            if (conditions.length > 0) {
                sqlQuery += ` WHERE ` + conditions.join(' AND ');
            }

            this.db.all(sqlQuery, params, (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(rows);
                }
            });
        });
    }

    // 删除数据集记录
    async deleteDataset(datasetId) {
        return new Promise((resolve, reject) => {
            const sqlDeleteDataset = `DELETE FROM datasets_cloud WHERE id = ?;`;
            this.db.run(sqlDeleteDataset, [datasetId], async (err) => {
                if (err) {
                    console.error('Error deleting dataset:', err.message);
                    reject({ code: -1, msg: err.message });
                }
                // 确认删除后则返回结果
                resolve({ code: 0, msg: 'Deleted OK' });
            });
        });
    }
}

module.exports = { DatasetsTableCloud };
